package com.terry.activity.controller.admin;

import com.terry.activity.bean.EntryModel;
import com.terry.activity.bean.constant.ErrorCode;
import com.terry.activity.bean.exception.DataAlreadyExistException;
import com.terry.activity.bean.exception.DataNotExistException;
import com.terry.activity.bean.exception.ParameterException;
import com.terry.activity.bean.message.ResponseMsg;
import com.terry.activity.controller.base.BaseController;
import com.terry.activity.service.IEntryService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * Create On 18/6/15.
 *
 * @author TerrySolar
 */
@Controller
@RequestMapping(value = "/admin")
@CrossOrigin
public class AdminEntryController extends BaseController {

    @Resource
    private IEntryService entryService;

    @ResponseBody
    @RequestMapping(value = "/entry", method = RequestMethod.GET)
    public ResponseMsg retrieveEntry(Long activityId, Long catalogId) {
        List<EntryModel> entryModels;

        if (catalogId != null) {
            entryModels = this.entryService.retrieveEntryOfActivityAndCatalog(activityId, catalogId);
        } else {
            entryModels = this.entryService.retrieveAllEntryOfActivity(activityId);
        }

        return responseData(entryModels);
    }

    @ResponseBody
    @RequestMapping(value = "/entry/add", method = RequestMethod.POST)
    public ResponseMsg addEntry(Long activityId, Long enrollId) throws DataAlreadyExistException, DataNotExistException {

        EntryModel entryModel = this.entryService.addEntry(activityId, enrollId);

        if (entryModel != null) {
            return responseOK();
        } else {
            return responseError(ErrorCode.ADMIN_ADD_ENTRY_ERROR, "系统错误");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/entry/create", method = RequestMethod.POST)
    public ResponseMsg addManualEntry(EntryModel entryModel) throws ParameterException, DataNotExistException {

        entryModel = this.entryService.addManualEntry(entryModel);

        return responseData(entryModel);
    }

    @ResponseBody
    @RequestMapping(value = "/entry/cancel", method = RequestMethod.POST)
    public ResponseMsg cancelEntry(Long activityId, Long enrollId) throws DataNotExistException {
        this.entryService.cancelEntry(activityId, enrollId);

        return responseOK();
    }

    @ResponseBody
    @RequestMapping(value = "/entry/delete", method = RequestMethod.POST)
    public ResponseMsg cancelEntry(Long entryId) {
        if (this.entryService.deleteEntry(entryId)) {
            return responseOK();
        } else {
            return responseError(ErrorCode.SERVER_ERROR, "删除失败");
        }
    }

}
